package com.potato369.cryptNacos.controller;

import com.potato369.cryptNacos.domain.User;
import com.potato369.cryptNacos.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Api(tags = "UserController", consumes = "用户管理")
@RestController
@RequestMapping("/users")
public class UserController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation("创建用户")
    @PostMapping("/create")
    public String createUser(@RequestBody User user) {
        User userRes = this.userService.save(user);
        if (Objects.isNull(userRes)) {
            return "失败";
        }
        return "成功";
    }

    @ApiOperation("删除一个用户")
    @DeleteMapping("/{id}/delete")
    public String deleteUser(@ApiParam(name = "用户id") @PathVariable Long id) {
        User user = this.userService.findOne(id);
        if (Objects.isNull(user)) {
            return "失败";
        }
        this.userService.delete(user);
        return "成功";
    }

    @ApiOperation("更新一个用户")
    @PutMapping("/{id}/update")
    public String updateUser(@ApiParam(name = "用户id") @PathVariable Long id, @RequestBody User user) {
        User userTmp = this.userService.findOne(id);
        if (Objects.isNull(userTmp)) {
            return "失败";
        }
        if (!Objects.isNull(user)) {
            if (user.getName() != null && !userTmp.getName().equals(user.getName())) {
                userTmp.setName(user.getName());
                userTmp.setUpdateTime(new Date());
            }
            if (user.getAge() != null && !userTmp.getAge().equals(user.getAge())) {
                userTmp.setAge(user.getAge());
                userTmp.setUpdateTime(new Date());
            }
        }
        User userRes = this.userService.update(userTmp);
        if (Objects.isNull(userRes)) {
            return "失败";
        }
        return "成功";
    }

    @ApiOperation("获取所有用户")
    @GetMapping("/list")
    public List<User> listUser() {
        return this.userService.findAll();
    }

    @ApiOperation("查找一个用户")
    @GetMapping("/{id}/find")
    public User findUser(@ApiParam(name = "用户id") @PathVariable Long id) {
        return this.userService.findOne(id);
    }
}
